package com.spzx.cart.service.impl;

import com.spzx.cart.domain.CartInfo;
import com.spzx.cart.service.ICartService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuPrice;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ICartServiceImpl implements ICartService {
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private RemoteProductService productService;
	private final String USER_CART_KEY = "user:cart:";

	@Override
	public void addToCart(Long skuId, Integer skuNum) {
		int maxNum = 99;
		// 获取用户id
		Long userId = SecurityUtils.getUserId();
		// 获取购物车信息
		String key = getCartKey(userId);
		BoundHashOperations<String, String, CartInfo> boundHashOperations
				= redisTemplate.boundHashOps(key);
		String skuIdKey = skuId.toString();
		Boolean hasKey = boundHashOperations.hasKey(skuIdKey);
		// 是否购物车包含商品
		if (hasKey) {
			// Num++
			CartInfo cartInfo = boundHashOperations.get(skuIdKey);
			if (cartInfo != null) {
				// TODO 做购物车商品最大数量限制
				int newNum = cartInfo.getSkuNum() + skuNum;
				newNum = Math.min(newNum, maxNum);
				cartInfo.setSkuNum(newNum);
				cartInfo.setUpdateTime(new Date());
				boundHashOperations.put(skuIdKey, cartInfo);
			}

		} else {
			// put新商品
			if ((boundHashOperations.size() + 1) > 5) {
				throw new RuntimeException("购物车最多添加5个商品");
			}
			CartInfo cartInfo = new CartInfo();
			cartInfo.setSkuId(skuId);
			skuNum = Math.min(skuNum, maxNum);
			cartInfo.setSkuNum(skuNum);
			SkuPrice price = productService.getSkuPrice(skuId, SecurityConstants.INNER).getData();
			cartInfo.setCartPrice(price.getSalePrice());
			// cartInfo.setSkuPrice(price.getSalePrice());
			// ProductSku productSku = productService.getProductSku(skuId, SecurityConstants.INNER).getData();
			// cartInfo.setThumbImg(productSku.getThumbImg());
			cartInfo.setUserId(userId);
			// cartInfo.setSkuName(productSku.getSkuName());
			cartInfo.setCreateTime(new Date());
			cartInfo.setUpdateTime(new Date());
			boundHashOperations.put(skuIdKey, cartInfo);
		}


	}

	@Override
	public List<CartInfo> cartList() {
		// 获取用户id
		Long userId = SecurityUtils.getUserId();
		// 获取购物车信息
		String key = getCartKey(userId);
		BoundHashOperations<String, String, CartInfo> cartListMap
				= redisTemplate.boundHashOps(key);
		List<CartInfo> cartList = cartListMap.values();
		if (cartList == null)
			return new ArrayList<>();

		cartList.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
		return cartList;
	}

	public List<CartInfo> cartListV2() {
		// 获取用户id
		Long userId = SecurityUtils.getUserId();
		// 获取购物车信息
		String key = getCartKey(userId);
		BoundHashOperations<String, String, CartInfo> cartListMap
				= redisTemplate.boundHashOps(key);
		List<CartInfo> cartList = cartListMap.values();
		if (cartList == null)
			return new ArrayList<>();
		cartList.stream().forEach(
				(cartRedisItem) -> {
					ProductSku productSku = productService.getProductSku(cartRedisItem.getSkuId(), SecurityConstants.INNER).getData();
					cartRedisItem.setSkuPrice(productSku.getSalePrice());
					cartRedisItem.setSkuName(productSku.getSkuName());
					cartRedisItem.setThumbImg(productSku.getThumbImg());
				}
		);
		cartList.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
		return cartList;
	}


	@Override
	public void clearCart() {
		redisTemplate.delete(getCartKey(SecurityUtils.getUserId()));
	}

	@Override
	public void deleteCartSku(Long skuId) {
		Long userId = SecurityUtils.getUserId();
		String key = getCartKey(userId);
		redisTemplate.boundHashOps(key).delete(skuId.toString());
	}

	@Override
	public void checkCart(Long skuId, Integer isChecked) {
		Long userId = SecurityUtils.getUserId();
		String key = getCartKey(userId);
		BoundHashOperations<String, String, CartInfo> cartListMap
				= redisTemplate.boundHashOps(key);
		CartInfo cartInfo = cartListMap.get(skuId.toString());
		cartInfo.setIsChecked(isChecked);
		cartListMap.put(skuId.toString(), cartInfo);
	}

	@Override
	public void allCheckCart(Integer isChecked) {
		Long userId = SecurityUtils.getUserId();
		String key = getCartKey(userId);
		BoundHashOperations<String, String, CartInfo> cartListMap
				= redisTemplate.boundHashOps(key);
		cartListMap.values().forEach(cartInfo -> {
			cartInfo.setIsChecked(isChecked);
			cartListMap.put(cartInfo.getSkuId().toString(), cartInfo);
		});
	}

	@Override
	public List<CartInfo> getCartCheckedList(Long userId) {
		// 获取购物车信息
		String key = getCartKey(userId);
		BoundHashOperations<String, String, CartInfo> cartListMap
				= redisTemplate.boundHashOps(key);
		List<CartInfo> cartList = cartListMap.values();
		if (cartList == null)
			return new ArrayList<>();
		List<CartInfo> collect = cartList.stream().filter((cartInfo) -> cartInfo.getIsChecked().equals(1)).map(
				(cartRedisItem) -> {
					ProductSku productSku = productService.getProductSku(cartRedisItem.getSkuId(), SecurityConstants.INNER).getData();
					cartRedisItem.setSkuPrice(productSku.getSalePrice());
					cartRedisItem.setSkuName(productSku.getSkuName());
					cartRedisItem.setThumbImg(productSku.getThumbImg());
					return cartRedisItem;
				}
		).sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())).collect(Collectors.toList());
		return collect;
	}

	@Override
	public void deleteCartCheckList(Long userId) {
		String cartKey = getCartKey(userId);
		BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
		List<CartInfo> cartCachInfoList = hashOperations.values();
		if (!CollectionUtils.isEmpty(cartCachInfoList)) {
			for (CartInfo cartInfo : cartCachInfoList) {
				// 获取选中的商品！
				if (cartInfo.getIsChecked().intValue() == 1) {
					hashOperations.delete(cartInfo.getSkuId().toString());
				}
			}
		}
	}

	private String getCartKey(Long userId) {
		return USER_CART_KEY + userId;
	}
}
